<?

/***************************************************************************
 Jupiter Content System @ Jupiterportal.com
 Copyright (C) 2005 Cosmin Flavius (highstrike@gmail.com)

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 More Info About The Licence At http://www.gnu.org/copyleft/gpl.html
****************************************************************************/

function b_shoutbox()
{
	$name_function = "b_shoutbox";

	global $a, $db, $blocks_db, $template, $language, $config, $misc, $PHP_SELF, $is_loged_in, $is_moderator, $is_administrator, $is_webmaster, $months, $days, $m, $y, $OnlineGuestsCount, $OnlineMembersCount;
	if(!file_exists("blocks/$name_function/language/{$config['language']}")) include "blocks/$name_function/language/en.php";
	else include "blocks/$name_function/language/{$config['language']}";

	$random_code = md5("$name_function");
	$random_code = substr("$random_code", 0, 5);

	if(!isset($content)) $content = NULL;
	if(!isset($_GET["$random_code"])) $_GET["$random_code"] = NULL;

	if($_GET["$random_code"] == "on") $_SESSION["$random_code"] = "on";
	elseif($_GET["$random_code"] == "off") $_SESSION["$random_code"] = "off";

	$query_string = "?{$_SERVER['QUERY_STRING']}";

	foreach($blocks_db as $blocks)
	{
		$block_code = md5("{$blocks['name']}");
		$block_code = substr("$block_code", 0, 5);

		$query_string = str_replace("&$block_code=off","", $query_string);
		$query_string = str_replace("&$block_code=on","", $query_string);
	}

	if($query_string == "?" || strpos($query_string, '=on') !== false || strpos($query_string, '=off') !== false) $code_query = "?";
	else $code_query = "$query_string&";

	if(!isset($_SESSION["$random_code"]) || $_SESSION["$random_code"] == "on") $links = "<a href='$code_query$random_code=off'><img src='templates/$template/images/misc/minus.gif' border='0'> {$language_block['Shout title']}</a>";
	elseif($_SESSION["$random_code"] == "off") $links = "<a href='$code_query$random_code=on'><img src='templates/$template/images/misc/plus.gif' border='0'> {$language_block['Shout title']}</a>";

	$template_block = implode("", file("templates/$template/block.php"));
	$template_block = str_replace("{template}", $template, $template_block);
	$template_block = str_replace("{links}", $links, $template_block);

	if(!isset($_SESSION["$random_code"]) || $_SESSION["$random_code"] == "on")
	{

// EDIT BELOW HERE

$scroll = $language_block['Shout scroll'];
$numofposts = $language_block['Shout postnum'];
$showdate = $language_block['Shout showdate'];
$badlang = $language_block['Shout badlang'];
$floodtime = $language_block['Shout floodtime'];

			$content .= "<script language=\"JavaScript\">";
			$content .= "function addsmiley(symbol) {";
			$content .= "  document.postshout.msg.value += symbol;";
			$content .= "  document.postshout.msg.focus();";
			$content .= "}";
			$content .= "</script>";

// FUNCTIONS BEGIN
// Write posted data to file
function writetofile($post1,$post2) {
								
$msgfilename = "includes/shout_messages.txt";
$curdate = date('Y/m/d H:i:s');
$save = file($msgfilename);
$filename = fopen($msgfilename, "r+");
$data = file_get_contents($msgfilename);

	$name_function = "b_shoutbox";

	global $a, $db, $blocks_db, $template, $language, $config, $misc, $PHP_SELF, $is_loged_in, $is_moderator, $is_administrator, $is_webmaster, $months, $days, $m, $y, $OnlineGuestsCount, $OnlineMembersCount;
	if(!file_exists("blocks/$name_function/language/{$config['language']}")) include "blocks/$name_function/language/en.php";
	else include "blocks/$name_function/language/{$config['language']}";
					$badlang = $language_block['Shout badlang'];
					if ($badlang == "1") {

								$post2 = str_replace("\n"," ",$post2);
								$post2 = do_censor($post2);

								fwrite($filename, $post1."\t".$post2."\t".$curdate."\t".$_SERVER['REMOTE_ADDR']."\t".$_SESSION['id']."\n");
								fwrite($filename, $data);
							
								fclose($filename);

								header('Location: '.$_SERVER['HTTP_REFERER'].'');
					
					} else if ($badlang == "0") {

								$post2 = str_replace("\n"," ",$post2);

								fwrite($filename, $post1."\t".$post2."\t".$curdate."\t".$_SERVER['REMOTE_ADDR']."\t".$_SESSION['id']."\n");
								fwrite($filename, $data);
							
								fclose($filename);
							
								header('Location: '.$_SERVER['HTTP_REFERER'].'');
					
					} else {
			
						$content .= "<tr><td class='con2' colspan='2' align='center' width='100%'><span class=alert>Invalid Bad Language Value</span></td></tr>";
			
					} // End If bad Language

} // End function

// Convert smilies to images
function smiles($messagetext) {

	$sm_search = array(":D",
					   ":)",
					   ":(",
					   ":o",
					   ":shock:",
					   ":-?",
					   "8)",
					   ":lol:",
					   ":x",
					   ":P",
					   ":redface:",
					   ":cry:",
					   ":evil:",
					   ":twisted:",
					   ":roll:",
					   ";)",
					   ":!:",
					   ":?:",
					   ":idea:",
					   ":arrow:",
					   ":arrowl:",
					   ":arrowd:",
					   ":arrowu:",
					   ":mrgreen:"
					   );
	$sm_replace = array("<img src=images/shout_emoticons/icon_cheesygrin.gif>",
						"<img src=images/shout_emoticons/icon_smile.gif>",
						"<img src=images/shout_emoticons/icon_sad.gif>",
						"<img src=images/shout_emoticons/icon_surprised.gif>",
						"<img src=images/shout_emoticons/icon_eek.gif>",
						"<img src=images/shout_emoticons/icon_confused.gif>",
						"<img src=images/shout_emoticons/icon_cool.gif>",
						"<img src=images/shout_emoticons/icon_lol.gif>",
						"<img src=images/shout_emoticons/icon_mad.gif>",
						"<img src=images/shout_emoticons/icon_razz.gif>",
						"<img src=images/shout_emoticons/icon_redface.gif>",
						"<img src=images/shout_emoticons/icon_cry.gif>",
						"<img src=images/shout_emoticons/icon_evil.gif>",
						"<img src=images/shout_emoticons/icon_twisted.gif>",
						"<img src=images/shout_emoticons/icon_rolleyes.gif>",
						"<img src=images/shout_emoticons/icon_wink.gif>",
						"<img src=images/shout_emoticons/icon_exclaim.gif>",
						"<img src=images/shout_emoticons/icon_question.gif>",
						"<img src=images/shout_emoticons/icon_idea.gif>",
						"<img src=images/shout_emoticons/icon_arrow.gif>",
						"<img src=images/shout_emoticons/icon_arrowl.gif>",
						"<img src=images/shout_emoticons/icon_arrowd.gif>",
						"<img src=images/shout_emoticons/icon_arrowu.gif>",
						"<img src=images/shout_emoticons/icon_mrgreen.gif>"
						);
	$myoutput = str_replace($sm_search, $sm_replace, $messagetext);
	
	return $myoutput; 

	}

// Word wrapping for messages.
function breakLongWords($str, $maxLength, $char){
    $wordEndChars = array(" ", "\n", "\r", "\f", "\v", "\0");
    $count = 0;
    $newStr = "";
    $openTag = false;
    for($i=0; $i<strlen($str); $i++){
        $newStr .= $str{$i};   
       
        if($str{$i} == "<"){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == ">")){
            $openTag = false;
            continue;
        }
       
        if(!$openTag){
            if(!in_array($str{$i}, $wordEndChars)){//If not word ending char
                $count++;
                if($count==$maxLength){//if current word max length is reached
                    $newStr .= $char;//insert word break char
                    $count = 0;
                }
            }else{//Else char is word ending, reset word char count
                    $count = 0;
            }
        }
       
    }//End for   
    return $newStr;
}
	
function real_wordwrap($string,$width,$break)
{
   $string = preg_replace('/([^\s]{'.$width.'})/i',"$1$break",$string);
   echo $string;
   return $string;
}
// FUNCTIONS END

if (isset($_POST["shout_delete"])) { // IF DELETE CLICKED
	
	if (isset($_POST["post"])) {
	
	// get file contents and create array elements by new lines
	$filename = "includes/shout_messages.txt";
	$read =	file_get_contents($filename);

	// Remove any extra lines
	$read = str_replace("\n\n","",$read);

	$array = explode ("\n",$read);
	
	// for every tick box remove element from array
	foreach($_POST["post"] as $value) {
		
		unset($array[$value]);

	}
	
	// Delete messages file and then recreate and insert existing posts.
	unlink($filename);
	$handle = fopen($filename, "x+");
	
	// for every array element left reinsert
	foreach($array as $renew) {
	$lines = count($array);

		fwrite($handle, $renew."\n");
	}

	fclose($handle);

// Fix double lines
$myfile = "includes/shout_messages.txt";
$mydata = file_get_contents($myfile);
//$fix = str_replace("\n\n","",$mydata);
$fix = substr_replace($mydata, "", -1);
$handle = fopen($myfile, "w");
fwrite($handle, $fix);
fclose($handle);


	
	header('location:'.$_SERVER['HTTP_REFERER']);
	}
	
}

	if (isset($_POST["shout_submit"])) {
		
		// Remove any tabs
		$_POST["name"] = str_replace("\t"," ",$_POST["name"]);
		$_POST["msg"] = str_replace("\t"," ",$_POST["msg"]);

		// Clean up strings
		$_POST["name"] = stripslashes(trim(htmlspecialchars($_POST["name"])));
		$_POST["msg"] = stripslashes(trim(htmlspecialchars($_POST["msg"])));

		if (!file_exists("includes/shout_messages.txt")) {
		
			$content .= "<tr><td class='con2' colspan='2' align='center' width='100%'>shout_messages.txt file doesn't exsist.</td></tr>";
		
		} else if ($_POST["name"] == "name" || $_POST["msg"] == "message" || $_POST["name"] == NULL || $_POST["msg"] == NULL) {
	
			$content .= "<tr><td class='con2' colspan='2' align='center' width='100%'><span class=alert>Please enter your message</span></td></tr>";
	
		} else {
		
			$filename = "includes/shout_messages.txt";
			$handle = fopen($filename,"r");
			$read = file_get_contents($filename);
		
			if ($read != "" || $read != NULL) {
					
					$array = explode("\n", $read);

					if ($array[0] != NULL || $array[0] != "") {
				
					list($name, $msg, $time, $ip) = explode("\t", $array[0]);
										
					$ip = trim($ip);
					
					// Convert timestamp to unix timestamp and get current unix timestamp
					$strtime = strtotime($time);
					$flood_gate_time = $strtime+$floodtime;
					$curtime = time();
					$valid = true;
					}
					
					if ($ip == $_SERVER['REMOTE_ADDR'] && $flood_gate_time > $curtime) {
						$content .= "<tr><td class='con2' colspan='2' align='center' width='100%'><span class=alert>You must wait ".$floodtime." secs</span></td></tr>";
					} else {

					writetofile($_POST["name"],$_POST["msg"]);
					
					}
					
			} else {
				writetofile($_POST["name"],$_POST["msg"]);
			}
			
		} // end if file exists
		
	} // end submit

		if(isset($is_loged_in))
		{
			$content .= "<form name='postshout' method='post' action='$PHP_SELF'><tr>";
			$content .= "<td class='con1' colspan='2' align='center' width='100%'><textarea name='msg' style='width:100%; height:50px;' maxlength='{$language_block['Shout maxchars']}' class='box'></textarea></td>";
			$content .= "</tr>";
			$content .= "<tr>";
			$content .= "<td class='con1' align='left'><input type='submit' name='shout_submit' style='width:100%' class='box' value='{$language_block['Shout submit']}'></td>";
			$content .= "<td class='con1' align='right'><input type='reset' style='width:100%' class='box' value='{$language_block['Shout reset']}'></td>";
			$content .= "</tr>";
			$content .= "<tr><td class='con1' align='center' colspan='2'>";
			$content .= "<a href=\"javascript:addsmiley(' :) ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_smile.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :lol: ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_lol.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :D ');\"><img src=\"images/shout_emoticons/icon_cheesygrin.gif\" width=\"15\" height=\"15\" border=\"0\" style=\"border: 0px;\"></a>&nbsp;<a href=\"javascript:addsmiley(' :P ');\"><img src=\"images/shout_emoticons/icon_razz.gif\" width=\"15\" height=\"15\" border=\"0\" style=\"border: 0px;\"></a>&nbsp;<a href=\"javascript:addsmiley(' ;) ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_wink.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :redface: ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_redface.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :o ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_surprised.gif\" width=\"15\" height=\"15\"></a><br>";
			$content .= "<a href=\"javascript:addsmiley(' :shock: ');\"><img src=\"images/shout_emoticons/icon_eek.gif\" width=\"15\" height=\"15\" border=\"0\" style=\"border: 0px;\"></a>&nbsp;<a href=\"javascript:addsmiley(' :( ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_sad.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :cry: ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_cry.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :roll: ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_rolleyes.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :x ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_mad.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :twisted: ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_twisted.gif\" width=\"15\" height=\"15\"></a>&nbsp;<a href=\"javascript:addsmiley(' :evil: ');\"><img style=\"border: 0px;\" src=\"images/shout_emoticons/icon_evil.gif\" width=\"15\" height=\"15\"></a>";
			$content .= "</td></tr>";
			$content .= "<input name='name' type='hidden' value='$_SESSION[username]'>";
			$content .= "</form>";
		}

	$filename = "includes/shout_messages.txt";

	if (file_exists($filename)) {
	
	$handle = fopen($filename, "r");
	$read = file_get_contents($filename);
	$x=0;

	// create array elements by new lines
	$array = explode ("\n",$read);

		// Start scrolling box if on
		if ($scroll == "1") {
			$content .= "<tr><td style='background: transparent; margin: 0px; padding: 0px;' align='center' colspan='2'>";

			// Add a scrolling div if more than 5 shouts
			if (count($array) > 6){
			$content .= "<div style='border: 0px solid #000000; margin: 0px; padding : 0px; width : auto; height : 235px; overflow : auto; overflow-x: hidden;'>";
			}

			$content .= "<table cellspacing='1' cellpadding='2' align='center' style='margin: 0px; font-family: Arial, Helvetica, sans-serif; width: 100%; border: 0px; font-size:11px;'>";
		}
	
	$page = isset($_GET['shouts']) ? $_GET['shouts'] : 1;

$numofposts = $language_block['Shout postnum'];

	$start = ($page-1) * $numofposts;

	// start loop for each page
	for ($i=$start; $i<$start+$numofposts; $i++) {
		
		if ($array[$i] != NULL || $array[$i] != "") {
			
			list($name, $msg, $date, $ip, $member_id) = explode("\t", $array[$i]);
					
			$date = str_replace(" ","/",$date);
			list($year,$month,$day,$time) = explode("/", $date);
			
			// convert text to smilies.
			$msg = smiles($msg);

			// Create links in message
			$msg = preg_replace("#([ ]|^|])([a-z]+?)://([a-z0-9@:\-]+)\.([a-z0-9@:\-.\~]+)((?:/[^ ]*)?[^][\".,?!;: ])#i", "\\1<a href=\"\\2://\\3.\\4\\5\" target=\"_blank\">[link]</a>", $msg);
			$msg = preg_replace("#([ ]|^|])www\.([a-z0-9\-]+)\.([a-z0-9:\-.\~]+)((?:/[^ ]*)?[^][\".,?!;: ])#i", "\\1<a href=\"http://www.\\2.\\3\\4\" target=\"_blank\">[link]</a>", $msg);
			$msg = preg_replace("#([ ]|^|])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+[^][\".,?!;: ])#i", "\\1<a href=\"mailto:\\2@\\3\">[email]</a>", $msg);

			// Fix message word wrapping
			$br = "<br>";

			// Show date, Yes or No.
			if ($showdate == "1") {
				$title = "title=\"Posted ".$day."/".$month."/".$year." ".$time."\"";
			} else {
				$title = "";
			}
			
				$x++;
			// IF SCROLL IS ON
			if ($scroll == "1") {
				if ( $x % 2 != 0 ) {
					if(isset($is_administrator) || isset($is_webmaster)){
						$content .= "<tr><td ".$title." class=\"con1\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr><tr><td ".$title." class=\"con1\"><form method=post style='margin:0px; padding:0px;'><input type='submit' name='shout_delete' style='width:100%' class='box' value='{$language_block['Shout delete']}'><input name='post[$i]' type='hidden' value='$i'></form></td></tr>";
					} else {	$content .= "<tr><td ".$title." class=\"con1\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr>";}
				} else {
					if(isset($is_administrator) || isset($is_webmaster)){
						$content .= "<tr><td ".$title." class=\"con2\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr><tr><td ".$title." class=\"con2\"><form method=post style='margin:0px; padding:0px;'><input type='submit' name='shout_delete' style='width:100%' class='box' value='{$language_block['Shout delete']}'><input name='post[$i]' type='hidden' value='$i'></form></td></tr>";
					} else {	$content .= "<tr><td ".$title." class=\"con2\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr>";}
				} 
			} else {
				if ( $x % 2 != 0 ) {
					if(isset($is_administrator) || isset($is_webmaster)){
						$content .= "<tr><td ".$title." class=\"con1\" colspan=\"2\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr><tr><td ".$title." class=\"con1\" colspan=\"2\"><form method=post style='margin:0px; padding:0px;'><input type='submit' name='shout_delete' style='width:100%' class='box' value='{$language_block['Shout delete']}'><input name='post[$i]' type='hidden' value='$i'></form></td></tr>";
					} else {	$content .= "<tr><td ".$title." class=\"con1\" colspan=\"2\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr>";}
				} else {
					if(isset($is_administrator) || isset($is_webmaster)){
						$content .= "<tr><td ".$title." class=\"con2\" colspan=\"2\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr><tr><td ".$title." class=\"con2\" colspan=\"2\"><form method=post style='margin:0px; padding:0px;'><input type='submit' name='shout_delete' style='width:100%' class='box' value='{$language_block['Shout delete']}'><input name='post[$i]' type='hidden' value='$i'></form></td></tr>";
					} else {	$content .= "<tr><td ".$title." class=\"con2\" colspan=\"2\"><div style=\"padding:1px;\"><b>&rsaquo;</b> <a href=\"index.php?n=modules/users&a=1&d=$member_id\"><b>".wordwrap($name,18,"<br>",1)."</b></a><div style=\"padding-top:4px;\">".breakLongWords($msg, 21, $br)."</div></div></td></tr>";}
				} 
			}
						
		} else {
		
		break;
		
		}
	}
	
	fclose($handle);
	
	}

		// End scrolling box if on
		if ($scroll == "1") {
			$content .= "</table>";

			if (count($array) > 6){
			$content .= "</div>";
			}

			$content .= "</td></tr>";
		}

// Take away the extra line with no data
$lineCount = count($array) - 1;

if($lineCount > $numofposts){
			$content .= "<tr>";
			$content .= "<td class='con1' colspan='2' align='center'>";

	$totalPages = ceil($lineCount / $numofposts);

	if ($page!=1 && $page!=$totalPages) $content .= "<a class=\"phpshout_link\" href=".$_SERVER['PHP_SELF']."?shouts=".($page-1).">< {$language_block['Shout previous']}</a> | <a class=\"phpshout_link\" href=".$_SERVER['PHP_SELF']."?shouts=".($page+1).">{$language_block['Shout next']} ></a>";
	
	else if ($page!=1) $content .= "<a class=\"phpshout_link\" href=".$_SERVER['PHP_SELF']."?shouts=".($page-1).">< {$language_block['Shout previous']}</a>";

	else if ($page!=$totalPages) $content .= "<a class=\"phpshout_link\" href=".$_SERVER['PHP_SELF']."?shouts=".($page+1).">{$language_block['Shout next']} ></a>";

			$content .= "</td>";
			$content .= "</tr>";
}
// EDIT ABOVE HERE

	}

	$template_block = str_replace("{content}", $content, $template_block);
	$output = $template_block;

return $output;
}

?>